package breeze.pixel.weather.apps_util.utils.appsettings.settingsview;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Switch;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.yalantis.ucrop.UCrop;

import java.io.File;

import breeze.pixel.weather.App;
import breeze.pixel.weather.R;
import breeze.pixel.weather.apps_util.utils.AppToolUtil;
import breeze.pixel.weather.apps_util.utils.MToast;
import breeze.pixel.weather.apps_util.utils.appsettings.AppSettings;
import breeze.pixel.weather.apps_util.views.mtoolbar.MToolbar;

public class DiyBackgroundPicView extends AppCompatActivity {

    private ImageView img_1, img_2;

    private AppSettings sets;

    private static final int _REQUEST_PICK_PICTURE_CODE_0 = 1234;

    private static final int _REQUEST_PICK_PICTURE_CODE_1 = 12345;

    @SuppressLint("UseSwitchCompatOrMaterialCode")
    private Switch turn_on_diy_bg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diy_background_pic_view);
        //实现状态栏沉浸
        getWindow().getDecorView().setSystemUiVisibility(1280);
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        //初始化设置类
        sets = AppSettings.getInstance(this);
        init();
        initData();
    }

    @SuppressLint("UseSwitchCompatOrMaterialCode")
    public void init() {
        MToolbar mToolbar = findViewById(R.id.sets_diy_bg_toolbar);
        mToolbar.setNavigation(R.mipmap.icon_back, v -> finish());
        img_1 = findViewById(R.id.set_diy_bg_img1);
        img_2 = findViewById(R.id.set_diy_bg_img2);
        turn_on_diy_bg = findViewById(R.id.set_diy_bg_switch);
    }

    public void initData() {
        MyOnClick onClick = new MyOnClick();
        sets = AppSettings.getInstance(this);
        //判断模式
        int backgroundMode = sets.getBackgroundModeType();
        boolean isUsingDiy = backgroundMode == 1;
        turn_on_diy_bg.setChecked(isUsingDiy);
        turn_on_diy_bg.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                toast("记得选择你的图片噢");
                sets.setBackgroundModeType(AppSettings.TYPE_BACKGROUNDMODE_CUSTOM);
            } else {
                sets.setBackgroundModeType(AppSettings.TYPE_BACKGROUNDMODE_DEFAULT);
            }
            update();
        });
        if (backgroundMode == 0) {//no picture
            img_1.setImageResource(R.mipmap.icon_no_pic);
            img_2.setImageResource(R.mipmap.icon_no_pic);
        }
        img_1.setOnClickListener(onClick);
        img_2.setOnClickListener(onClick);
        String img1 = AppToolUtil.getMainBackgroundPic(this);
        String img2 = AppToolUtil.getDrawerBackgroundPic(this);
        if (new File(img1).exists()) {
            img_1.setImageBitmap(BitmapFactory.decodeFile(img1));
        }
        if (new File(img2).exists()) {
            img_2.setImageBitmap(BitmapFactory.decodeFile(img2));
        }
    }

    private void toast(String msg) {
        MToast.show(this, msg);
    }

    private void selectBitmap(int type) {
        if (ActivityCompat.checkSelfPermission(DiyBackgroundPicView.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            startActivityForResult(intent, type);
        } else {
            ActivityCompat.requestPermissions(DiyBackgroundPicView.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
            toast("没有储存权限");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,  int[] grantResults) {
        if (requestCode == 0) {
            toast("获取权限成功");
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == _REQUEST_PICK_PICTURE_CODE_0 && resultCode == Activity.RESULT_OK) {
            //背景图片1
            UCrop.of(data.getData(), Uri.fromFile(new File(AppToolUtil.getMainBackgroundPic(App.getContext())))).withAspectRatio(1000, 2000).start(DiyBackgroundPicView.this);
        } else if (requestCode == _REQUEST_PICK_PICTURE_CODE_1 && resultCode == Activity.RESULT_OK) {
            UCrop.of(data.getData(), Uri.fromFile(new File(AppToolUtil.getDrawerBackgroundPic(App.getContext())))).withAspectRatio(900, 500).start(DiyBackgroundPicView.this);
        }
        initData();
        update();
    }

    class MyOnClick implements View.OnClickListener {
        @SuppressLint("NonConstantResourceId")
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.set_diy_bg_img1:
                    selectBitmap(_REQUEST_PICK_PICTURE_CODE_0);
                    break;
                case R.id.set_diy_bg_img2:
                    selectBitmap(_REQUEST_PICK_PICTURE_CODE_1);
                    break;
            }
        }
    }

    private void update() {
        Intent intent = new Intent(AppSettings._ACTION_UPDATE_MAINVIEW_BACKGROUND);
        sendBroadcast(intent);
    }

}